package com.xposed.openfire.smack;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.xposed.openfire.smack.abstracts.AbstractBaseActivity;
import com.xposed.openfire.smack.adapter.ChatMessageAdapter;
import com.xposed.openfire.smack.entity.ChatMessage;
import com.xposed.openfire.smack.entity.ChatMessageDao;
import com.xposed.openfire.smack.xmpp.XmppConnection;


import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ChatMessageActivity extends AbstractBaseActivity {

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.edit_content)
    EditText editContent;

    private String userName;

    private ChatMessageAdapter messageAdapter;
    private LinearLayoutManager layoutManager;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_chat_session;
    }

    @Override
    protected void initView() {

        userName = getIntent().getStringExtra(Constants.BUNDLE_KEY_USER_NAME);
        if (TextUtils.isEmpty(userName)) {
            return;
        }
        List<ChatMessage> messages = APPOpenfireSmack.getDaoSession().getChatMessageDao()
                .queryBuilder().where(ChatMessageDao.Properties.Name.eq(userName)).list();
        messageAdapter = new ChatMessageAdapter((this), messages);
        layoutManager = new LinearLayoutManager((this));
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(messageAdapter);
    }

    @Override
    public void onEventMainThread(Object object) {
        super.onEventMainThread(object);
        if (object instanceof ChatMessage) {
            layoutManager.scrollToPositionWithOffset(messageAdapter.getItemCount(), 0);
            messageAdapter.addItem((ChatMessage) object);
        }
    }

    @OnClick({R.id.btn_send})
    public void onViewClicked(View view) {
        String content = editContent.getText().toString();
        if (TextUtils.isEmpty(content)) {
            Toast.makeText((this), ("内容不能为空"), Toast.LENGTH_SHORT).show();
            return;
        }
        if (!TextUtils.isEmpty(content)) {
            XmppConnection.getInstance().sendChatMessage(userName, content);
            editContent.setText(null);
        }
    }


}
